package org.wevil.controller.sys;

import org.wevil.entity.sys.SysOrg;
import org.wevil.enumu.ResultEnum;
import org.wevil.params.add.OrgAP;
import org.wevil.params.update.OrgUP;
import org.wevil.service.sys.OrgService;
import org.wevil.util.BeanUtil;
import org.wevil.util.NodeUtil;
import org.wevil.vo.Result;
import org.wevil.vo.node.OrgNodeVo;
import org.wevil.vo.node.OrgNodeWxVo;
import org.wevil.vo.list.OrgListVo;
import org.wevil.vo.node.NodeVo;



import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Validated
/** 组织管理 */
@RestController
@RequestMapping("org")
public class OrgController {

    @Resource
    OrgService orgService;

    /** 组织列表 */
    @GetMapping("/list")
    public Result<List<OrgListVo>> list() {
        List<OrgListVo> data = orgService.getOrgList();
        return Result.success(data);
    }

    /** 获取下级组织列表 */
    @GetMapping("/sublist")
    public Result<List<OrgListVo>> sublist(
            @RequestParam  Integer orgId
    ) {
        List<OrgListVo> data = orgService.getSubOrgList(orgId);
        return Result.success(data);
    }

    /** 组织节点 */
    @GetMapping("/node")
    public Result<List<? extends NodeVo>> node() {
        List<OrgNodeVo> nodeList = orgService.getOrgNodeList();
        List<? extends NodeVo> data = NodeUtil.listWithTree(nodeList);
        return Result.success(data);
    }

    /** 组织节点-小程序 */
    @GetMapping("/node/wx")
    public Result<List<? extends NodeVo>> nodeWx() {
        List<OrgNodeWxVo> nodeList = orgService.getOrgNodeWxList();
        List<? extends NodeVo> data = NodeUtil.listWithTree(nodeList);
        return Result.success(data);
    }

    /** 新增组织 */
    @PostMapping("/addOrg")
    public Result<String> addOrg(
            @RequestBody @Validated OrgAP param
    ) {
        SysOrg entity = new SysOrg();
        BeanUtil.copyPropIgnoreNull(param, entity);
        orgService.addOrg(entity);
        return Result.success();
    }

    /** 删除组织 */
    @DeleteMapping("/delOrg")
    public Result<String> delOrg(
            @RequestParam  Integer orgId
    ) {
        boolean b = orgService.haveLowerLevel(orgId);
        if(b){
            return Result.info(ResultEnum.ERROR, "有下级组织，无法删除");
        }
        orgService.delOrg(orgId);
        return Result.success();
    }

    /** 修改组织 */
    @PutMapping("/updateOrg")
    public Result<String> updateOrg(
            @RequestBody @Validated OrgUP param
    ) {
        orgService.updateOrg(param);
        return Result.success();
    }

}
